package com.hehui.module.customer.service.impl;

import com.hehui.module.customer.dao.CustomerTypeMapper;
import com.hehui.module.customer.entity.CustomerType;
import com.hehui.module.customer.service.ICustomerTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class CustomerTypeServiceImpl implements ICustomerTypeService {

    @Autowired
    private CustomerTypeMapper customerTypeMapper;

    @Override
    public List<CustomerType> selectCustomerType(CustomerType customerType) {

        return customerTypeMapper.selectAllList(customerType);
    }

    @Override
    public int insertCustomerType(CustomerType customerType) {

        if (customerType.getIsdef().equals("0")){
            //如果新添加的客户类型被设置为默认，那么久要先修改之前默认为非默认
            customerTypeMapper.setUndefault(customerType.getMerchantId());
        }
        return customerTypeMapper.insertSelective(customerType);
    }

    @Override
    public int deleteCustomerTypeById(Long customerTypeId) {
        return customerTypeMapper.deleteByPrimaryKey(customerTypeId);
    }

    //校验类型下是否存在客户   不存在返回 true;
    @Override
    public boolean checkHasCustomerByTypeId(Long customerTypeId) {
        return customerTypeMapper.checkHasCustomerByTypeId(customerTypeId).size() == 0 ? true : false;
    }

    @Override
    public CustomerType selectByPrimaryKey(Long customerTypeId) {
        return customerTypeMapper.selectByPrimaryKey(customerTypeId);
    }

    //校验类型名的唯一性 如果不唯一  返回 true;
    @Override
    public boolean checkCustomerTypeNameUnique(String typeName, Long merchantId) {
        return customerTypeMapper.checkCustomerTypeNameUnique(typeName, merchantId).size() > 0 ? true : false;
    }

    @Override
    public int updateByPrimaryKeySelective(CustomerType customerType) {
        if (customerType.getIsdef().equals("0")){
            //如果修改的客户类型被设置为默认，那么久要先修改之前默认为非默认
            customerTypeMapper.setUndefault(customerType.getMerchantId());
        }
        return customerTypeMapper.updateByPrimaryKeySelective(customerType);
    }


    /*
     *生成一个新的编号
     */
    @Override
    public String createNewNum(Long merchantId) {
        String lastNum = customerTypeMapper.getMaxNum(merchantId);
        if (lastNum == null || lastNum.equals("")) {
            lastNum = "1000";
        }
        return Integer.parseInt(lastNum) + 1 + "";
    }

    //校验类型编号的唯一性 如果不唯一  返回 true;
    @Override
    public boolean checkCustomerTypeNumUnique(String typeNum, Long merchantId) {
        return customerTypeMapper.checkCustomerTypeNumUnique(typeNum, merchantId).size() > 0 ? true : false;
    }
}
